package com.cloudcc.cloudframe.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 万能viewholder
 * 
 * @author wangzhiqiang
 * @date 2015-7-10 上午9:51:10
 * 
 */
public class ViewHolder {

	/**
	 * 控件
	 */
	private SparseArray<View> mViews;
	private Context mContext;
	private int mPostion;
	private View mConvertView;

	private ViewHolder(Context context, ViewGroup parent, int layoutId,
			int postion) {
		this.mContext = context;
		this.mPostion = postion;
		this.mViews = new SparseArray<View>();
		mConvertView = LayoutInflater.from(mContext).inflate(layoutId, parent,
				false);
		mConvertView.setTag(this);
	}

	public static ViewHolder get(Context context, View convertView,
			ViewGroup parent, int layoutId, int postion) {
		if (convertView == null) {
			return new ViewHolder(context, parent, layoutId, postion);
		} else {
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.mPostion = postion;
			return holder;
		}
	}

	public View getConvertView() {
		return mConvertView;
	}

	/**
	 * 通过id获取view
	 * 
	 * @param viewId
	 * @return
	 */
	public <T extends View> T getView(int viewId) {

		View v = mViews.get(viewId);
		if (v == null) {
			v = mConvertView.findViewById(viewId);
			mViews.put(viewId, v);
		}
		return (T) v;
	}

	/**
	 * 设置 TextView 以及子类Button的文字
	 * 
	 * @param viewId
	 * @param text
	 * @return
	 */
	public ViewHolder setText(int viewId, String text) {
		if (TextUtils.isEmpty(text)) {
			return this;
		}
		TextView tv = (TextView) getView(viewId);
		tv.setText(text);
		return this;
	}
	/**
	 * 设置 TextView 以及子类Button的文字
	 * 
	 * @param viewId
	 * @param text
	 * @return
	 */
	public ViewHolder setText(int viewId, String text,String defaultText) {
		if (TextUtils.isEmpty(text)) {
			text =defaultText;
		}
		TextView tv = (TextView) getView(viewId);
		tv.setText(text);
		return this;
	}
	/** 设置 imageview的 图片
	 * @param viewId
	 * @param resId
	 * @return
	 */
	public ViewHolder setSrc(int viewId, int resId) {
		ImageView iv =getView(viewId);
		iv.setImageResource(resId);
		return this;
	}
	/** 设置 显示隐藏
	 * @param viewId
	 * @param visibility
	 * @return
	 */
	public ViewHolder setVisibility(int viewId, int visibility) {
		View iv =getView(viewId);
		iv.setVisibility(visibility);
		return this;
	}

	public int getPostion() {
		return mPostion;
	}
	
	

}
